import React, { useImperativeHandle, useMemo, useState } from 'react';
import MyIcon from '@/components/MyIcon';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Empty, Timeline, Tooltip, Badge, Space, Button, message, Spin } from 'antd';
import { useContext, useEffect } from 'react';
import { ISupplierActionEnum, SupplierLocaldataContext } from '../common';
import pageStyles from '@/common/pageLayout.less';
import { getColorTextLoadMap, onMouseOutBtn, searchChangeColor, tooltipLength } from '@/utils';
import { ImageCarousel } from '@/components/ImageCarousel';
import { UpCircleOutlined, DownCircleOutlined, EditOutlined } from '@ant-design/icons';
import cls from 'classnames';
import { memoirDataGridServices } from '../services';

// const memoirData = [
//   //模拟数据-王志龙
//   {
//     isOpen: '0',
//     id: 'memoir-1',
//     memoirTypeName: '成立和注册||#f8e71c',
//     memoirType: '100131061000',
//     memoirNature: '1',
//     memoirTime: '2015-05-06 14:15:13',
//     memoirImage:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.8a91b07a4ea5a76a862ba00cb7338fff?rik=rO3i7Ygjh266kw&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202204%2f25%2f651e0fef-6a01-44c1-bfec-f66475b6dd95.jpg.1&ehk=056d%2bqrtogvHi7CPZXFnBI17ywEH1s0ULakCDtEE9VE%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.0bc7079fff7368cf98e2b44a625a4305?rik=Lmr6qBnEJ1DwGg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202108%2f30%2f849ae23f-7b07-4f79-8c20-e5788ef1766e.jpg.1&ehk=pDlrRDy6hsD6Wkh6m7eOL5bQAQFX5Pt9SyE56GJ7XxQ%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.b3df9e4ffb6c80e0488d69b9c5c87600?rik=IrxvFMGoY4Y9SA&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202203%2f28%2fe48d5c4e-b79a-46c3-bddf-4742ebf881f7.jpg.1&ehk=FcOmyqgVOyK71wHiIX2Nn5W%2bC0rX0yNNJu27CjMKAYc%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.7988dc2ef34470ebb88cf807613a9210?rik=S6TtNAZOlYYu%2fg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202103%2f29%2f4b1e0021-425a-4cf6-842e-9b5d9106c835.jpg.1&ehk=peYES8%2ftsDMmoYn566jnRhAc535aexA0nz%2b7xAgbIMY%3d&risl=&pid=ImgRaw&r=0',
//     memoirInfo:
//       '据大湾区之声微博：香港特区政府发展局6月12日宣布成立北部都会区统筹办事处（北都办），以统筹、倡导及推动北部都会区的发展。同时，特区政府宣布，丘卓恒即日起出任北都办主任。发展局发言人表示，北部都会区以“国际创科新城”为主题，集优质生活、产业发展和文化休闲于一体，是驱动香港再创高峰的新引擎，亦是促进香港与大湾区高质量经济合作，融入国家发展大局的重要平台。发展局发言人称，北部都会区计划涵盖土地发展、房屋供应、交通基建建设、生态保育、产业发展，以及政府及小区设施等领域，其规模巨大，特区政府多个政策局和部门均会参与，北都办将承担整体统筹和推动的工作。',
//     memoirResult:
//       '此前，美国前情报官员大卫·查尔斯·格鲁施向美国国会和情报界监察长举报，称美国政府已经发现外星飞船，并利用其零件和技术制造武器。然而，美国国防部发言人苏珊·高夫在一份声明中称：“迄今为止，尚未证实过去或目前存在任何关于政府拥有外星材料或进行逆向工程的说法。”',
//     createTime: '2016-02-15 12:16:18',
//     createrName: '测试1',
//     createPositionName: '测试岗位1',
//     createDepartmentName: '测试部门1',
//   },
//   {
//     isOpen: '1',
//     id: 'memoir-2',
//     memoirTypeName: '重要合同业务||#417505',
//     memoirType: '100131061003',
//     memoirNature: '2',
//     memoirTime: '2015-05-06 14:15:13',
//     memoirImage:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.8a91b07a4ea5a76a862ba00cb7338fff?rik=rO3i7Ygjh266kw&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202204%2f25%2f651e0fef-6a01-44c1-bfec-f66475b6dd95.jpg.1&ehk=056d%2bqrtogvHi7CPZXFnBI17ywEH1s0ULakCDtEE9VE%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.0bc7079fff7368cf98e2b44a625a4305?rik=Lmr6qBnEJ1DwGg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202108%2f30%2f849ae23f-7b07-4f79-8c20-e5788ef1766e.jpg.1&ehk=pDlrRDy6hsD6Wkh6m7eOL5bQAQFX5Pt9SyE56GJ7XxQ%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.b3df9e4ffb6c80e0488d69b9c5c87600?rik=IrxvFMGoY4Y9SA&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202203%2f28%2fe48d5c4e-b79a-46c3-bddf-4742ebf881f7.jpg.1&ehk=FcOmyqgVOyK71wHiIX2Nn5W%2bC0rX0yNNJu27CjMKAYc%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.7988dc2ef34470ebb88cf807613a9210?rik=S6TtNAZOlYYu%2fg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202103%2f29%2f4b1e0021-425a-4cf6-842e-9b5d9106c835.jpg.1&ehk=peYES8%2ftsDMmoYn566jnRhAc535aexA0nz%2b7xAgbIMY%3d&risl=&pid=ImgRaw&r=0',
//     memoirInfo:
//       '据大湾区之声微博：香港特区政府发展局6月12日宣布成立北部都会区统筹办事处（北都办），以统筹、倡导及推动北部都会区的发展。同时，特区政府宣布，丘卓恒即日起出任北都办主任。发展局发言人表示，北部都会区以“国际创科新城”为主题，集优质生活、产业发展和文化休闲于一体，是驱动香港再创高峰的新引擎，亦是促进香港与大湾区高质量经济合作，融入国家发展大局的重要平台。发展局发言人称，北部都会区计划涵盖土地发展、房屋供应、交通基建建设、生态保育、产业发展，以及政府及小区设施等领域，其规模巨大，特区政府多个政策局和部门均会参与，北都办将承担整体统筹和推动的工作。',
//     memoirResult:
//       '此前，美国前情报官员大卫·查尔斯·格鲁施向美国国会和情报界监察长举报，称美国政府已经发现外星飞船，并利用其零件和技术制造武器。然而，美国国防部发言人苏珊·高夫在一份声明中称：“迄今为止，尚未证实过去或目前存在任何关于政府拥有外星材料或进行逆向工程的说法。”',
//     createTime: '2016-02-15 12:16:18',
//     createrName: '测试2',
//     createPositionName: '测试岗位2',
//     createDepartmentName: '测试部门2',
//   },
//   {
//     isOpen: '0',
//     id: 'memoir-3',
//     memoirTypeName: '重要合同业务||#417505',
//     memoirType: '100131061003',
//     memoirNature: '2',
//     memoirTime: '2015-05-06 14:15:13',
//     memoirImage:
//       'https://ts1.cn.mm.bing.net/th/id/R-C.8a91b07a4ea5a76a862ba00cb7338fff?rik=rO3i7Ygjh266kw&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202204%2f25%2f651e0fef-6a01-44c1-bfec-f66475b6dd95.jpg.1&ehk=056d%2bqrtogvHi7CPZXFnBI17ywEH1s0ULakCDtEE9VE%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.0bc7079fff7368cf98e2b44a625a4305?rik=Lmr6qBnEJ1DwGg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202108%2f30%2f849ae23f-7b07-4f79-8c20-e5788ef1766e.jpg.1&ehk=pDlrRDy6hsD6Wkh6m7eOL5bQAQFX5Pt9SyE56GJ7XxQ%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.b3df9e4ffb6c80e0488d69b9c5c87600?rik=IrxvFMGoY4Y9SA&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202203%2f28%2fe48d5c4e-b79a-46c3-bddf-4742ebf881f7.jpg.1&ehk=FcOmyqgVOyK71wHiIX2Nn5W%2bC0rX0yNNJu27CjMKAYc%3d&risl=&pid=ImgRaw&r=0||https://ts1.cn.mm.bing.net/th/id/R-C.7988dc2ef34470ebb88cf807613a9210?rik=S6TtNAZOlYYu%2fg&riu=http%3a%2f%2fpaper.chinahightech.com%2fpc%2fpic%2f202103%2f29%2f4b1e0021-425a-4cf6-842e-9b5d9106c835.jpg.1&ehk=peYES8%2ftsDMmoYn566jnRhAc535aexA0nz%2b7xAgbIMY%3d&risl=&pid=ImgRaw&r=0',
//     memoirInfo:
//       '据大湾区之声微博：香港特区政府发展局6月12日宣布成立北部都会区统筹办事处（北都办），以统筹、倡导及推动北部都会区的发展。同时，特区政府宣布，丘卓恒即日起出任北都办主任。发展局发言人表示，北部都会区以“国际创科新城”为主题，集优质生活、产业发展和文化休闲于一体，是驱动香港再创高峰的新引擎，亦是促进香港与大湾区高质量经济合作，融入国家发展大局的重要平台。发展局发言人称，北部都会区计划涵盖土地发展、房屋供应、交通基建建设、生态保育、产业发展，以及政府及小区设施等领域，其规模巨大，特区政府多个政策局和部门均会参与，北都办将承担整体统筹和推动的工作。',
//     memoirResult:
//       '此前，美国前情报官员大卫·查尔斯·格鲁施向美国国会和情报界监察长举报，称美国政府已经发现外星飞船，并利用其零件和技术制造武器。然而，美国国防部发言人苏珊·高夫在一份声明中称：“迄今为止，尚未证实过去或目前存在任何关于政府拥有外星材料或进行逆向工程的说法。”',
//     createTime: '2016-02-15 12:16:18',
//     createrName: '测试2',
//     createPositionName: '测试岗位2',
//     createDepartmentName: '测试部门2',
//   },
// ];

export const MemoirRightTabsPane = React.forwardRef(
  ({ allOpenChildren, changeOpenChildren, clickOpenClose, showUpdateMemoirModal }: SupplierManageAPI.IMemoirRightTabsPane, ref) => {
    /** 获取上下文 */
    const { updateFixCls, memoirImageRenderID, memoirDataList, curRes, locationID, supplierDispath, supplierInfoObj } = useContext(SupplierLocaldataContext);

    /** 保存搜索输入值 */
    const [memoirSearchValues, setMemoirSearchValues] = useState<Record<string, any>>({
      memoirResult: '',
      memoirInfo: '',
    });

    /** 保存搜索前原始值 */
    const [searchAfterDataList, setSearchAfterDataList] = useState<Record<string, any>[]>([]);

    /** 初始化 */
    useEffect(() => {
      if (memoirDataList?.length > 0) {
        //模拟数据-王志龙
        const allOpenIDList: string[] = memoirDataList?.map((item: any) => (item?.id ? item?.id : item?.key));
        changeOpenChildren({
          allOpenKeys: allOpenIDList,
          openIdKey: [allOpenIDList?.[0]],
        });
      }
    }, [memoirDataList?.length]); //模拟数据-王志龙

    /**
     * 接口回调
     * @param res
     */
    const memoirDataGridCallback = (res: any) => {
      if (res && res?.msgFlag) {
        if (res?.rows?.length > 0) {
          supplierDispath({
            type: ISupplierActionEnum.MEMOIRDATA_LIST,
            payload: res?.rows,
          });
        }
      } else {
        message.error(res?.msg);
      }
    };

    /** 获取资质列表 */
    const { memoirPaneloading, getMemoirPaneDataGrid, refreshMemoirPane } = memoirDataGridServices(curRes, locationID, memoirDataGridCallback);

    /** ref 返回事件 */
    useImperativeHandle(ref, () => ({
      refreshMemoirPane,
      getMemoirPaneDataGrid,
      searchMemoir,
      reloadMemoir,
    }));

    /**初始化 */
    useEffect(() => {
      if (locationID) {
        getMemoirPaneDataGrid({}); //模拟数据-王志龙
      }
    }, [locationID]);

    /**
     * 点击搜索
     * @param params
     */
    const searchMemoir = (params: Record<string, any>) => {
      if (supplierInfoObj && supplierInfoObj?.id) {
        getMemoirPaneDataGrid(params);
      } else {
        if (searchAfterDataList && searchAfterDataList?.length == 0) {
          setSearchAfterDataList(memoirDataList); //模拟数据-王志龙
        }
        const newSearchList: Record<string, any>[] = memoirDataList?.filter((item: any) => {
          //模拟数据-王志龙
          return item?.memoirResult?.includes(params?.memoirResult) || item?.memoirInfo?.includes(params?.memoirInfo);
        });
        supplierDispath({
          type: ISupplierActionEnum.MEMOIRDATA_LIST,
          payload: newSearchList,
        });
      }

      setMemoirSearchValues(params);
    };

    /**刷新 */
    const reloadMemoir = () => {
      if (supplierInfoObj && supplierInfoObj?.id) {
        getMemoirPaneDataGrid({});
      } else {
        supplierDispath({
          type: ISupplierActionEnum.MEMOIRDATA_LIST,
          payload: searchAfterDataList,
        });
      }
      setMemoirSearchValues({
        memoirResult: '',
        memoirInfo: '',
      });
    };

    /** 判断编辑按钮权限 */
    const editMemoirBtn = useMemo(() => {
      let showBtn: boolean = false;
      if (curRes?.['/supplierMemoirController/edit']) {
        if (supplierInfoObj && supplierInfoObj?.id) {
          if (supplierInfoObj?.isBlack == '0' && !supplierInfoObj?.cancelerID) {
            showBtn = true;
          }
        } else {
          showBtn = true;
        }
      }
      return showBtn;
    }, [curRes, supplierInfoObj]);

    return (
      <div className="commonTabsBodyDom">
        <Spin spinning={memoirPaneloading}>
          {memoirDataList?.length > 0 ? ( //模拟数据-王志龙
            <ScrollBarLayout style={{ margin: '5px 0px' }}>
              <div className={updateFixCls + 'memoirTimelineSty'}>
                <Timeline>
                  {memoirDataList?.map((item: any, index: number) => {
                    //模拟数据-王志龙
                    /** 事件类型 */
                    const memoirTypeName = getColorTextLoadMap(item?.memoirTypeName);

                    /** 事件图片 */
                    const itemImageList: string[] = item?.memoirImage ? item?.memoirImage?.split('||') : [];

                    return (
                      <Timeline.Item key={`${index}-memoirKey`} dot={<MyIcon style={{ fontSize: 18 }} type="icon-time-circle" />}>
                        <div style={{ margin: '5px 0px' }}>
                          事件于【
                          <span className={updateFixCls + 'memoirTimelineSty-titleTimeBoxSty'}>{item?.memoirTime}</span>
                          】发生，具体情况如下：
                          <a
                            onClick={() => {
                              clickOpenClose(item?.id || item?.key, allOpenChildren);
                            }}
                          >
                            {allOpenChildren?.openIdKey?.includes(item?.id || item?.key) ? <UpCircleOutlined /> : <DownCircleOutlined />}
                          </a>
                        </div>
                        {allOpenChildren?.openIdKey?.includes(item?.id || item?.key) && (
                          <div className={updateFixCls + 'memoirTimelineSty-bodyBoxsty'}>
                            <Badge.Ribbon
                              text={memoirTypeName?.colorText}
                              color={memoirTypeName?.color}
                              placement="start"
                              style={{
                                top: '10px',
                              }}
                            >
                              <div className={cls(pageStyles['commonDlListSty'], `${updateFixCls}operateBtnAnimarion`)}>
                                <ImageCarousel imageStrList={itemImageList} imageRenderDomID={memoirImageRenderID} />

                                <dl>
                                  <dt>
                                    <MyIcon type="icon-jiezhishijian" />
                                    &nbsp;是否有效：
                                  </dt>
                                  <dd
                                    style={{
                                      color: item?.isOpen == '1' ? '#52c41a' : item?.isOpen == '0' ? '#ff0003' : '',
                                    }}
                                  >
                                    {item?.isOpen == '1' ? '是' : item?.isOpen == '0' ? '否' : '--'}
                                  </dd>
                                  {/* <dt>
                                  <MyIcon type="icon-leixing1" />
                                  &nbsp;事件类型：
                                </dt>
                                <dd style={{ color: memoirTypeName?.color || '' }}>
                                  {memoirTypeName?.colorText || '--'}
                                </dd> */}

                                  <dt>
                                    <MyIcon type="icon-time" />
                                    &nbsp;记录时间：
                                  </dt>
                                  <dd>{item?.createTime || '--'}</dd>
                                </dl>
                                <dl>
                                  <dt>
                                    <MyIcon type="icon-bumen" />
                                    &nbsp;记录部门：
                                  </dt>
                                  <dd>{item?.createDepartmentName || '--'}</dd>
                                  <dt>
                                    <MyIcon type="icon-lianxiren" />
                                    &nbsp;记录人：
                                  </dt>
                                  <dd>{item?.createrName || '--'}</dd>
                                </dl>
                                <dl>
                                  <dt>
                                    <MyIcon type="icon-zongjie1" />
                                    &nbsp;事件结果：
                                  </dt>
                                  <dd>
                                    <Tooltip autoAdjustOverflow={false} title={searchChangeColor(item?.memoirResult, memoirSearchValues?.memoirResult)}>
                                      {item?.memoirResult ? searchChangeColor(tooltipLength(item?.memoirResult, 100), memoirSearchValues?.memoirResult) : '--'}
                                    </Tooltip>
                                  </dd>
                                </dl>
                                <dl style={{ paddingBottom: 10 }}>
                                  <dt>
                                    <MyIcon type="icon-baogao" />
                                    &nbsp;事件描述：
                                  </dt>
                                  <dd>
                                    <Tooltip autoAdjustOverflow={false} title={searchChangeColor(item?.memoirInfo, memoirSearchValues?.memoirInfo)}>
                                      {item?.memoirInfo ? searchChangeColor(tooltipLength(item?.memoirInfo, 100), memoirSearchValues?.memoirInfo) : '--'}
                                    </Tooltip>
                                  </dd>
                                </dl>
                                {editMemoirBtn && (
                                  <Space direction="vertical" size={[0, 8]} className={`${updateFixCls}operateBtnAnimarion-editDelOtherBtn`}>
                                    <Button
                                      onMouseOut={onMouseOutBtn}
                                      onClick={() => {
                                        showUpdateMemoirModal({
                                          showModal: true,
                                          checkRows: item,
                                        });
                                      }}
                                      // icon={<EditOutlined />}
                                    >
                                      编辑
                                    </Button>
                                  </Space>
                                )}
                              </div>
                            </Badge.Ribbon>
                          </div>
                        )}
                      </Timeline.Item>
                    );
                  })}
                </Timeline>
              </div>
            </ScrollBarLayout>
          ) : (
            <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无数据" />
          )}
        </Spin>
      </div>
    );
  },
);
